package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 每日礼包
type ShopDiamon struct {
	BaseM
	Uid    bson.ObjectId   `bson:"_id" json:"_id"`       // 用户uid
	BuyCnt map[int64]int64 `bson:"buyCnt" json:"buyCnt"` // 购买次数，key是购买道具tid
}

func NewShopDiamon() cache.EntryI {
	return &ShopDiamon{
		BuyCnt: make(map[int64]int64),
	}
}

// 保存信息
func (sd *ShopDiamon) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("ShopDiamon", bson.M{"_id": sd.Uid}, sd)
	if err != nil {
		return err
	}
	return
}

func (sd *ShopDiamon) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		sd.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		sd.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "ShopDiamon_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return sd.LoadData()
}

// 加载数据
func (sd *ShopDiamon) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("ShopDiamon", bson.M{"_id": sd.Uid}, nil, &sd)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if sd.BuyCnt == nil {
		sd.BuyCnt = make(map[int64]int64)
	}
	return
}

// 更新数据
func (sd *ShopDiamon) Update(val *ShopDiamon) {
	Cache.Put("ShopDiamon", val.Uid.Hex(), val)
	val.UpdateData()
}

// 获取每日礼包信息
func (u *User) GetShopDiamon() *ShopDiamon {
	v, _ := Cache.Get("ShopDiamon", u.Uid.Hex())
	return v.(*ShopDiamon)
}
